// 回射服务器基本模型
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define BACKLOG 20
#define PORT 8888
#define BUFFSIZE 4096
void upper(char buffer[], int len);
void processClient(int clientFd);
int main(void)
{
    int serverFd;
    serverFd = socket(AF_INET, SOCK_STREAM, 0);
    if (serverFd > 0)
    {
        printf("socket created successed.\n");
    }
    else
    {
        printf("socket created failed.\n");
        exit(-1);
    }
    struct sockaddr_in serverAddr;
    memset(&serverAddr, 0, sizeof(serverAddr));
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(PORT);
    serverAddr.sin_addr.s_addr = INADDR_ANY;
    int error = bind(serverFd, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
    if (error == 0)
    {
        printf("bind successed.\n");
    }
    else
    {
        printf("bind failed.\n");
        exit(-1);
    }
    error = listen(serverFd, BACKLOG);
    if (error == 0)
    {
        printf("listen successed.\n");
    }
    else
    {
        printf("listen failed.\n");
        exit(-1);
    }
    struct sockaddr_in clientAddr;
    socklen_t clientAddrLen = sizeof clientAddr;
    int clientFd = accept(serverFd, (struct sockaddr*)&clientAddr, &clientAddrLen);
    if (clientFd > 0)
    {
        printf("new connection:\n");
        printf("port: %d\n", clientAddr.sin_port);
        char* ip = inet_ntoa(clientAddr.sin_addr);
        printf("ipv4: %s\n", ip);
        processClient(clientFd);
    }
    else
    {
        printf("accept failed.\n");
        exit(-1);
    }
    return 0;
}
void upper(char buffer[BUFFSIZE], int len)
{
    for (int i = 0; i < len; ++i)
    {
        if (buffer[i] < 97 || buffer[i] > 122)
        {
            continue;
        }
        buffer[i] -= 32;
    }
}
void processClient(int clientFd)
{
    char buffer[BUFFSIZE] = "welcome to my server.\n";
    send(clientFd, buffer, strlen(buffer), 0);
    while (1)
    {
        int n = recv(clientFd, buffer, sizeof buffer, 0);
        printf("%s\n", buffer);
        printf("recv %d bytes data altogether.\n", n);
        upper(buffer, strlen(buffer));
        send(clientFd, buffer, strlen(buffer)+1, 0);
    }
}